var E = window.wangEditor
var editor = new E('#div1', '#div3')
let whiteList = ['https://dskj001.oss-cn-shenzhen.aliyuncs.com','https://hlq1.oss-cn-hangzhou.aliyuncs.com']
var activeImg

editor.customConfig.menus = [
    'head',  // 标题
    'bold',  // 粗体
    'fontSize',  // 字号
    'fontName',  // 字体
    'italic',  // 斜体
    'underline',  // 下划线
    'strikeThrough',  // 删除线
    'foreColor',  // 文字颜色
    'backColor',  // 背景颜色
    'link',  // 插入链接
    'list',  // 列表
    'justify',  // 对齐方式
    'quote',  // 引用
    'emoticon',  // 表情
    'image',  // 插入图片
    'table',  // 表格
    'video',  // 插入视频
    'code',  // 插入代码
    'undo',  // 撤销
    'redo'
]

editor.customConfig.colors = [
  '#ffffff',
  '#000000',
  '#EEECE1',
  '#1F497D',
  '#4F81BD',
  '#C0504D',
  '#9BBB59',
  '#8064A2',
  '#4BACC6',
  '#F79646',
  '#F2F2F2',
  '#7F7F7F',
  '#DDD9C3',
  '#eeece0',
  '#1c487f',
  '#4d80bf',
  '#c24f4a',
  '#8baa4a',
  '#7b5ba1',
  '#46acc8',
  '#f9963b',
  '#C6D9F0',
  '#DBE5F1',
  '#F2DCDB',
  '#EBF1DD',
  '#E5E0EC',
  '#DBEEF3',
  '#FDEADA',
  '#D8D8D8',
  '#595959',
  '#DDD9C3',
  '#8DB3E2',
  '#B8CCE4',
  '#E5B9B7',
  '#D7E3BC',
  '#CCC1D9',
  '#B7DDE8',
  '#FBD5B5',
  '#BFBFBF',
  '#3F3F3F',
  '#938953',
  '#548DD4',
  '#95B3D7',
  '#D99694',
  '#C3D69B',
  '#B2A2C7',
  '#92CDDC',
  '#FAC08F',
  '#A5A5A5',
  '#262626',
  '#17365D',
  '#953734',
  '#76923C',
  '#5F497A',
  '#31859B',
  '#E36C09',
  '#7F7F7F',
  '#0C0C0C',
  '#1D1B10',
  '#0F243E',
  '#244061',
  '#632423',
  '#4F6128',
  '#3F3151',
  '#974806',
  '#C00000',
  '#FF0000',
  '#92D050',
  '#00B050',
  '#00B0F0',
  '#0070C0',
  '#002060',
  '#7030A0'
]

editor.customConfig.linkImgCallback = function (url) {
  editor.txt.html(matchImg(editor.txt.html()))
  uploadImgs()
}

editor.customConfig.onblur = function (html) {
  // console.log('onblur');
  // clickImg()
}


// 粘贴回调
editor.customConfig.pasteTextHandle =function (content) {
  let matchArr = content.match(/<img.*?src="(.*?)".*?\/?>/ig)

  if (Array.isArray(matchArr) && matchArr.length === 1) {
    let div = document.createElement('div')

    div.innerHTML = content
    if(div.children.length  === 1){
      return ''
    }
  }

  content =  content.replace(/<\/?a.*?>/g, '');

  let index = content.indexOf('img')
  content  = isWordDocument(content) ? filterPasteWord(content) : content;

  if(index !== -1){
    setTimeout(function () {
      // console.log('回调');
      uploadImgs()
    },300)
  }
  return matchImg(content)
}

document.getElementById('div3').addEventListener("paste",async function (e){
  let cbd = e.clipboardData;
  let ua = window.navigator.userAgent;

  // 如果是 Safari 直接 return
  if ( !(e.clipboardData && e.clipboardData.items) ) {
    return;
  }

  // Mac平台下Chrome49版本以下 复制Finder中的文件的Bug Hack掉
  if(cbd.items && cbd.items.length === 2 && cbd.items[0].kind === "string" && cbd.items[1].kind === "file" &&
    cbd.types && cbd.types.length === 2 && cbd.types[0] === "text/plain" && cbd.types[1] === "Files" &&
    ua.match(/Macintosh/i) && Number(ua.match(/Chrome\/(\d{2})/i)[1]) < 49){
    return;
  }

  for(var i = 0; i < cbd.items.length; i++) {
    let item = cbd.items[i];
    if(item.kind == "file") {
      console.log(item);
      let blob = item.getAsFile();
     let res = await updateImg(blob)
      if(!res)  continue

      let img = `<img src="${res}"> `
      editor.cmd.do('insertHTML', matchImg(img))
      clickImg()
    }
  }

});

editor.customConfig.onchangeTimeout = 1000

editor.customConfig.onchange = async function (content) {
  localStorage.setItem('editText',content)
}


// 上传所有 没上传的图片
async function uploadImgs() {
  console.log('上传图片');
  // 创建一个虚拟容器
  let divEl = document.createElement('div')
  divEl.innerHTML = editor.txt.html()

  // 找出所有图片
  let imgAll = divEl.querySelectorAll("img"),
    changeImg = false

  for (let item of imgAll) {
    let url = item.getAttribute('dictionaries_url')

    // 判断域名是否白名单
    let whiteListIndex = whiteList.findIndex((val) => {
      // console.log(item.src, val);
      return item.src.indexOf(val) !== -1
    })

    // console.log(whiteListIndex);
    // 白名单不通过 或者 没有上传的图片
    if (Number(whiteListIndex) !== -1 || !url) continue


    // console.log(url);

    // let base64 = await getBase64(url, 'png')
    //
    // let blob = await dataURLtoBlob(base64);
    // console.log(blob);
    res = await getImg(url)

    if(!res){
      let cuowu = document.createElement('p')
      cuowu.innerText =  '上传失败，请重新上传'
      item.parentElement.appendChild(cuowu)
    }else{
      // console.log(item.parentElement);
      let imgBtn = item.parentElement.querySelector('.editor-image-menu')
      imgBtn && (imgBtn.style.display = 'block')
      // console.log(imgBtn);
    }
    // console.dir(item);

    item.src = res
    // console.log(item.src);
    editor.txt.html(divEl.innerHTML)
  }
  editor.txt.html(divEl.innerHTML)
  clickImg()
}

function clickImg() {
  let arr = document.querySelector('#div3 .w-e-text').querySelectorAll(".pgc-image .editor-image-menu-item")
  // console.log(arr);
  for (let item of arr) {
    item.onclick = function (e) {
      // console.log(e);
      for (let item of  e.path) {
        if (item.className === "pgc-img-wrapper") {
          activeImg = item.children[0]
          // cropper.replace('http://p3.pstatp.com/large/pgc-image/2f97151a40514bbeab83b6da25d2bfad')
          cropper.replace(activeImg.src)
          // console.log(activeImg.src);
          document.querySelector('.pop-up-model').style.display = "flex"
          openActionBtn()
          activeImg = item.children[0]
        }
      }
      clickImg()
    }
  }

  let inputArr = document.querySelector('#div3 .w-e-text').querySelectorAll(".pgc-image .pgc-img-caption-wrapper .pgc-img-caption-ipt")
  for(let item of inputArr){
    item.onfocus = function(){
      console.log(editor);
      editor.config.paste = false
      editor.$textElem.attr('contenteditable', false)
    }
    item.onblur = function(e){
      editor.config.paste = true
      item.parentElement.querySelector('.pgc-img-caption').innerHTML = e.target.value
      // console.log(e.target.value);
      editor.$textElem.attr('contenteditable', true)
    }
  }

  let colseArr = document.querySelector('#div3 .w-e-text').querySelectorAll(".pgc-image .pgc-img-wrapper .ttcore-remove-blot")
  for(let item of colseArr){
    // console.log(item);
    item.onclick = function (e) {
      for (let item of  e.path) {
        // console.log(item.className);
        if (item.className === "pgc-image pgc-card-fixWidth") {
          document.querySelector('#div3 .w-e-text').removeChild(item.parentElement)

          // console.log(item.parentElement);
        }
      }
    }
  }
}


editor.create()



function saveEdit(editor){
  let htmlStr =  editor.txt.html()
  let elDiv = document.createElement('div')
  elDiv.innerHTML = htmlStr



  let imgEl =  elDiv.querySelectorAll('.pgc-image')

  for(let item of imgEl){
    let img = item.getElementsByTagName('IMG') && item.getElementsByTagName('IMG')[0]
    let input = item.querySelector('.pgc-img-caption')

    let src = img && img.src
    let text = (input && input.innerHTML) || ''
    item.parentNode.className = "pgc-img"
    item.parentNode.innerHTML = saveImgEl(src,text);
  }

  let text = elDiv.innerHTML

  // text = text.toString()
  return text
}

function isElementNode(node) {
  return node.nodeType === 1;
}

function elCharacters(el) {
    let children = el.childNodes;

    for(let item of [...children]){
      if(isElementNode(item)){
        isNeedImg(item);
        elCharacters(item);
      }else{
        item.textContent = replaceSymbol(item.textContent);
      }
    }

    return el
}

function replaceSymbol(text){
  let str = text
  if(text){
    str = str.replace(/'/g,'’');
    str = str.replace(/"/g,'“');
    str = str.replace(/:/g,'：');
  }

  return str
}


function saveImgEl(src,text) {
  let str = `<img class="" src="${src}" ><p class="pgc-img-caption">${text}</p>`
  return str
}


  //是否是word过来的内容
  function isWordDocument(str) {
    return /(class="?Mso|style="[^"]*\bmso\-|w:WordDocument|<(v|o):|lang=)/gi.test(
      str
    );
  }

  var utils = {
    transUnitToPx: function(val) {
      if (!/(pt|cm)/.test(val)) {
        return val;
      }
      var unit;
      val.replace(/([\d.]+)(\w+)/, function(str, v, u) {
        val = v;
        unit = u;
      });
      switch (unit) {
        case "cm":
          val = parseFloat(val) * 25;
          break;
        case "pt":
          val = Math.round(parseFloat(val) * 96 / 72);
      }
      return val + (val ? "px" : "");
    }
  }


  //去掉小数
  function transUnit(v) {
    v = v.replace(/[\d.]+\w+/g, function(m) {
      return utils.transUnitToPx(m);
    });
    return v;
  }

  function filterPasteWord(str) {
    return (
      str
        .replace(/[\t\r\n]+/g, " ")
        .replace(/<!--[\s\S]*?-->/gi, "")
        //转换图片
        .replace(/<v:shape [^>]*>[\s\S]*?.<\/v:shape>/gi, function(str) {
          //opera能自己解析出image所这里直接返回空
          if (browser.opera) {
            return "";
          }
          try {
            //有可能是bitmap占为图，无用，直接过滤掉，主要体现在粘贴excel表格中
            if (/Bitmap/i.test(str)) {
              return "";
            }
            var width = str.match(/width:([ \d.]*p[tx])/i)[1],
              height = str.match(/height:([ \d.]*p[tx])/i)[1],
              src = str.match(/src=\s*"([^"]*)"/i)[1];
            return (
              '<img width="' +
              transUnit(width) +
              '" height="' +
              transUnit(height) +
              '" src="' +
              src +
              '" />'
            );
          } catch (e) {
            return "";
          }
        })
        //针对wps添加的多余标签处理
        .replace(/<\/?div[^>]*>/g, "")
        //去掉多余的属性
        .replace(/v:\w+=(["']?)[^'"]+\1/g, "")
        .replace(
          /<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|xml|meta|link|style|\w+:\w+)(?=[\s\/>]))[^>]*>/gi,
          ""
        )
        .replace(
          /<p [^>]*class="?MsoHeading"?[^>]*>(.*?)<\/p>/gi,
          "<p><strong>$1</strong></p>"
        )
        //去掉多余的属性
        .replace(/\s+(class|lang|align)\s*=\s*(['"]?)([\w-]+)\2/gi, function(
          str,
          name,
          marks,
          val
        ) {
          //保留list的标示
          return name == "class" && val == "MsoListParagraph" ? str : "";
        })
        //清除多余的font/span不能匹配&nbsp;有可能是空格
        .replace(/<(font|span)[^>]*>(\s*)<\/\1>/gi, function(a, b, c) {
          return c.replace(/[\t\r\n ]+/g, " ");
        })
        //处理style的问题
        .replace(/(<[a-z][^>]*)\sstyle=(["'])([^\2]*?)\2/gi, function(
          str,
          tag,
          tmp,
          style
        ) {
          var n = [],
            s = style
              .replace(/^\s+|\s+$/, "")
              .replace(/&#39;/g, "'")
              .replace(/&quot;/gi, "'")
              .replace(/[\d.]+(cm|pt)/g, function(str) {
                return utils.transUnitToPx(str);
              })
              .split(/;\s*/g);

          for (var i = 0, v; (v = s[i]); i++) {
            var name,
              value,
              parts = v.split(":");

            if (parts.length == 2) {
              name = parts[0].toLowerCase();
              value = parts[1].toLowerCase();
              if (
                (/^(background)\w*/.test(name) &&
                  value.replace(/(initial|\s)/g, "").length == 0) ||
                (/^(margin)\w*/.test(name) && /^0\w+$/.test(value))
              ) {
                continue;
              }

              switch (name) {
                case "mso-padding-alt":
                case "mso-padding-top-alt":
                case "mso-padding-right-alt":
                case "mso-padding-bottom-alt":
                case "mso-padding-left-alt":
                case "mso-margin-alt":
                case "mso-margin-top-alt":
                case "mso-margin-right-alt":
                case "mso-margin-bottom-alt":
                case "mso-margin-left-alt":
                //ie下会出现挤到一起的情况
                //case "mso-table-layout-alt":
                case "mso-height":
                case "mso-width":
                case "mso-vertical-align-alt":
                  //trace:1819 ff下会解析出padding在table上
                  if (!/<table/.test(tag))
                    n[i] =
                      name.replace(/^mso-|-alt$/g, "") + ":" + transUnit(value);
                  continue;
                case "horiz-align":
                  n[i] = "text-align:" + value;
                  continue;

                case "vert-align":
                  n[i] = "vertical-align:" + value;
                  continue;

                case "font-color":
                case "mso-foreground":
                  n[i] = "color:" + value;
                  continue;

                case "mso-background":
                case "mso-highlight":
                  n[i] = "background:" + value;
                  continue;

                case "mso-default-height":
                  n[i] = "min-height:" + transUnit(value);
                  continue;

                case "mso-default-width":
                  n[i] = "min-width:" + transUnit(value);
                  continue;

                case "mso-padding-between-alt":
                  n[i] =
                    "border-collapse:separate;border-spacing:" +
                    transUnit(value);
                  continue;

                case "text-line-through":
                  if (value == "single" || value == "double") {
                    n[i] = "text-decoration:line-through";
                  }
                  continue;
                case "mso-zero-height":
                  if (value == "yes") {
                    n[i] = "display:none";
                  }
                  continue;
                //                                case 'background':
                //                                    break;
                case "margin":
                  if (!/[1-9]/.test(value)) {
                    continue;
                  }
              }

              if (
                /^(mso|column|font-emph|lang|layout|line-break|list-image|nav|panose|punct|row|ruby|sep|size|src|tab-|table-border|text-(?:decor|trans)|top-bar|version|vnd|word-break)/.test(
                  name
                ) ||
                (/text\-indent|padding|margin/.test(name) &&
                  /\-[\d.]+/.test(value))
              ) {
                continue;
              }

              n[i] = name + ":" + parts[1];
            }
          }
          return (
            tag +
            (n.length
              ? ' style="' + n.join(";").replace(/;{2,}/g, ";") + '"'
              : "")
          );
        })
    );
  }





